#include <stdint.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include "module.h"
#include <stdint.h>
#include <sys/types.h>
#include <sys/time.h>
#include <time.h>
#include <sys/select.h>
#include "autoconfig.h"

int audio_present(uint32_t ms)
{
	struct timeval tv;
	int audio_fd = -1;
	
	audio_fd = open("/dev/audio", O_RDWR | O_NONBLOCK);
	if (audio_fd < 0) return -1;


	if (ms) {
		tv.tv_sec = 0;
		tv.tv_usec = tv.tv_usec = ms * 1000;
	}
		
	fd_set readfds;
	FD_ZERO(&readfds);
	FD_SET(audio_fd, &readfds);
	if (select(audio_fd + 1, &readfds, NULL, NULL, ms ?&tv:NULL) <= 0) return 0;

        return 1;
}

int audio_read(uint8_t * buffer, size_t len, int timeout)
{
	int audio_fd = -1;
	
	audio_fd = open("/dev/audio", O_RDWR | O_NONBLOCK);
	if (audio_fd < 0) return -1;
	
        if (buffer && len) {
                fd_set readfds;
                struct timeval tvp, *vp;
                int maxfd, readcount, ret = 0 ;

                maxfd = audio_fd;
                maxfd ++;
                readcount = 0 ;
                if (timeout == 0) {
                        vp = NULL;
                }
                else {
                        tvp.tv_sec = timeout / 1000;
                        tvp.tv_usec = (timeout % 1000) * 1000 ;
                        vp = &tvp;
                }
                while (readcount < len) {
                        FD_ZERO(&readfds) ;
                        FD_SET(audio_fd, &readfds) ;
                        ret = select(maxfd, &readfds, NULL, NULL, vp) ;
                        if (ret <= 0) {
                                break;
                        }
                        if (FD_ISSET(audio_fd, &readfds)) {
                                ret = read(audio_fd, buffer + readcount, len - readcount);
                                if (ret <= 0) {
                                        break ;
                                }
                                readcount += ret ;
                        }
                }
                return readcount;
        }
        return 0;
}
int audio_write(uint8_t *buf, uint32_t size)
{
	int audio_fd = -1;
	
	audio_fd = open("/dev/audio", O_RDWR | O_NONBLOCK);
	if (audio_fd < 0) return -1;
	
	return write(audio_fd, buf, size);
}


